const db = require('../db');

const SupplierModel = {
    // 获取所有正常供应商（排除软删除）
    async getAll() {
        const [rows] = await db.execute('SELECT * FROM suppliers WHERE status != 2');
        return rows;
    },

    // 根据ID获取供应商
    async getById(id) {
        const [rows] = await db.execute('SELECT * FROM suppliers WHERE id = ? AND status != 2', [id]);
        return rows[0];
    },

    // 创建供应商
    async create(supplier) {
        const sql = `
            INSERT INTO suppliers
            (name, type, level, tax_number, legal_person, legal_phone, contact_person, contact_phone, bank_account, address, remarks, status)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        `;
        const params = [
            supplier.name,
            supplier.type,
            supplier.level,
            supplier.tax_number,
            supplier.legal_person,
            supplier.legal_phone,
            supplier.contact_person,
            supplier.contact_phone,
            supplier.bank_account,
            supplier.address,
            supplier.remarks,
            supplier.status ?? 1  // 默认正常状态
        ];
        const [result] = await db.execute(sql, params);
        return { id: result.insertId, ...supplier };
    },

    // 更新供应商信息
    async update(id, supplier) {
        const sql = `
            UPDATE suppliers SET
                                 name = ?,
                                 type = ?,
                                 level = ?,
                                 tax_number = ?,
                                 legal_person = ?,
                                 legal_phone = ?,
                                 contact_person = ?,
                                 contact_phone = ?,
                                 bank_account = ?,
                                 address = ?,
                                 remarks = ?,
                                 status = ?
            WHERE id = ?
        `;
        const params = [
            supplier.name,
            supplier.type,
            supplier.level,
            supplier.tax_number,
            supplier.legal_person,
            supplier.legal_phone,
            supplier.contact_person,
            supplier.contact_phone,
            supplier.bank_account,
            supplier.address,
            supplier.remarks,
            supplier.status ?? 1,
            id
        ];
        await db.execute(sql, params);
        return { id, ...supplier };
    },

    // 软删除供应商
    async delete(id) {
        await db.execute('UPDATE suppliers SET status = 2 WHERE id = ?', [id]);
        return true;
    }
};

module.exports = SupplierModel;
